<template>
    <div class="container2">
        <!-- 客户其他地址dialog-->
        <el-dialog
            :title="title"
            width="570px"
            class="tableDialog"
            :close-on-click-modal="false"
            v-dialogDrag
            :visible.sync="viewVisible"
        >
            <section class="title">
                <p>{{ addressForm.names }}</p>
                <p>
                    <el-button
                        size="mini"
                        type="primary"
                        @click="init('add',addressForm)"
                        v-if="hasPermission('company:company:add')"
                    >添加收货地址
                    </el-button
                    >
                </p>
            </section>

            <el-table
                size="mini"
                v-loading="loading"
                :data="tableData"
                style="width: 100%; margin-top: 15px"
                border
                :header-cell-style="{
      'background-color': '#eeeeee !important',
      }"
                :row-class-name="tableRowClassName"
            >
                <el-table-column type="index" label="序号" width="60">
                </el-table-column>
                <el-table-column prop="" label="说明">
                    <template slot-scope="scope">
                        <section>
                            {{ scope.row.addressNames }}
                            {{ scope.row.detailAddress }}

                            <span v-if="scope.row.isDefault === '1'" style="color: #1890ff"
                            >默认</span
                            >
                            <span v-else style="color: #999999">默认</span>
                        </section>
                    </template>
                </el-table-column>
                <el-table-column p label="操作" width="112px">
                    <template slot-scope="scope">
                        <el-link
                            type="primary"
                            :underline="false"
                            @click="init('edit', scope.row)"
                            v-if="hasPermission('company:company:edit')"
                        >修改
                        </el-link
                        >
                        <el-link type="primary" :underline="false" @click="del(scope.row.id)"
                                 v-if="hasPermission('company:company:delete')"
                        >删除
                        </el-link>
                    </template>
                </el-table-column>
            </el-table>
            <!--      <span slot="footer" class="dialog-footer" v-if="method != 'view'">-->
            <!--        <el-button size="small" type="primary" @click="doSubmit()" v-noMoreClick-->
            <!--        >确定</el-button-->
            <!--        >-->
            <!--        <el-button size="small" @click="close()">取消</el-button>-->
            <!--      </span>-->
        </el-dialog>
        <el-dialog
            class="addressDialog"
            style="margin-top: 100px !important"
            top="15vh"
            :title="editTitle"
            width="570px"
            :close-on-click-modal="false"
            v-dialogDrag
            :visible.sync="editVisible"
        >
            <el-form
                label-width="105px"
                :rules="dataRule"
                ref="editForm"
                :model="editForm"
            >
                <el-form-item label="地址简称:" prop="addressName">
                    <el-input v-model="editForm.addressName" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="所属组织:" prop="agencyId">
                    <el-select clearable v-model="editForm.agencyId" placeholder="请选择组织">
                        <el-option
                            v-for="item in selectData"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="经纬度:" prop="GPSLatitude">
                    <div>
                        <el-input v-model="editForm.lat" placeholder="请输入经度"></el-input>
                        <el-input v-model="editForm.lng" placeholder="请输入纬度"></el-input>
                    </div>
                    <span>
                        <el-link icon="el-icon-search" @click="openBMap" type="danger">不知道经纬度，打开地图查找</el-link>
                    </span>
                </el-form-item>
                <el-form-item label="所在地区:" prop="countyCode">
                    <Area class="areaselect-adjust" ref="area" @getArea="getArea1"></Area>
                </el-form-item>
                <el-form-item label="详细地址:" prop="detailAddress">
                    <el-input v-model="editForm.detailAddress"></el-input>
                </el-form-item>
                <el-form-item label="默认地址:" prop="isDefault">
                    <el-switch
                        v-model="editForm.isDefault"
                        active-value="1"
                        inactive-value="0"
                    >
                    </el-switch>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="doSubmit()" v-noMoreClick
        >确定</el-button
        >
        <el-button size="small" @click="close('edit')">取消</el-button>
      </span>
        </el-dialog>



        <el-dialog
            class="mapDialog"
            style="margin-top: 100px !important"
            top="15vh"
            title="搜索地点"
            width="1000px"
            :close-on-click-modal="false"
            v-dialogDrag
            :visible.sync="mapVisible"
        >
            <BMap ref="BMap"
                  v-on:getlngAndlat="getlngAndlat"></BMap>

        </el-dialog>
    </div>
</template>
<script>
    import {
        editCompanyArea,
        getCompanyArea,
        deleteAddress,
        officeSelectData,
        getAddressById
    } from '@/api/market/crm.js';
    import Area from '@/components/area/area'
    import BMap from '@/components/BMap/BMap'

    export default {
        components: {
            Area,
            BMap
        },
        data() {
            return {
                selectData: [],
                method: '',
                title: '',
                editTitle: '',
                loading: false,
                mapVisible: false,
                tableData: [],
                id: '',
                addressForm: {
                    names: '',
                    companyId: ''
                },
                address_detail: null, //详细地址
                userlocation: {lng: "", lat: ""},
                lng: "",
                lat: "",
                editForm: {
                    agencyId: '',
                    props: 0,
                    lng: "",
                    lat: "",
                    addressName: '',
                    detailAddress: '',
                    isDefault: '',
                    contactName: '',
                    companyId: '',
                    contactPhone: '',
                    id: ''
                },
                editVisible: false,
                viewVisible: false,
                dataRule: {
                    isDefault: [{required: false, message: '请选择', trigger: 'change'}],
                    countyCode: [
                        {required: true, message: '请输入公司所在地区', trigger: 'blur'}
                    ],
                    agencyId: [
                        {required: true, message: '请选择所属组织', trigger: 'blur'}
                    ],
                    addressName: [
                        {required: true, message: '请输入地址简称', trigger: 'blur'},
                        {max: 10, message: '最大长度是10个字符', trigger: 'blur'}
                    ],
                    detailAddress: [
                        {required: true, message: '请输入详细地址', trigger: 'blur'},
                        {max: 50, message: '最大长度是50个字符', trigger: 'blur'}
                    ]
                }
            };
        },
        methods: {
        	handleClose(done) {
				this.$Msg.confirm({
					title:'您确定要关闭吗？',
					content:this.GLOBAL.FORM_CLOSE_TIPS,
					confirmCall:()=>{
						done();
					}
				})
			},
            openBMap() {
                this.mapVisible = true;
                console.log(val)
            },
            getlngAndlat(val) {
                this.mapVisible = false;
                this.editForm.lat = val.lat.toString();
                this.editForm.lng = val.lng.toString();
            },
            getSelectList() {
                officeSelectData({}).then((res) => {
                    if (res.data.code === '200') {
                        this.selectData = res.data.result
                    }
                })
            },
            // 校验手机号
            checkPhoneNumber(rule, value, callback) {
                if (value && (!(/^[1][34578]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
                    callback(new Error('手机号码不符合规范'))
                } else {
                    callback()
                }
            },
            init(method, addressForm, id) {
                this.getSelectList();
                if (method === 'view') {
                    this.viewVisible = true
                    let addressFormBuffer = {
                        names: addressForm.names,
                        companyId: addressForm.id
                    }
                    this.addressForm = addressFormBuffer
                    this.editForm.companyId = addressFormBuffer.companyId
                    this.getList(this.addressForm.companyId)
                    this.addressForm.id = ''
                    this.addressForm.addressId = ''
                    this.title = '查看收货地址'
                } else if (method === 'add') {
                    this.editForm.id = ''
                    this.editTitle = '添加收货地址'
                    this.editVisible = true
                    let that = this
                    this.$nextTick(() => {
                        this.$refs.editForm.resetFields()
                        this.editForm = {}
                        console.log('添加收货地址')
                        console.log(this.editForm.companyId)
                        that.$refs.area.province = ''
                        that.$refs.area.city = ''
                        that.$refs.area.district = ''
                    })
                    console.log(this.editForm.companyId)
                } else if (method === 'edit') {
                    console.log(id);
                    getAddressById({
                        id: id
                    }).then((res) => {
                        if (res.data.code === '200') {
                            this.editVisible = true
                            this.editForm = res.data.result
                            let area = JSON.parse(this.editForm.countyCode)
                            console.log(area)
                            let that = this
                            this.$nextTick(() => {
                                that.$refs.area.province = area.province
                                that.$refs.area.city = area.city
                                that.$refs.area.district = area.district
                            })
                            this.editTitle = '添加收货地址';
                        }
                    })
                    // this.editVisible = true
                    // this.editForm.id = addressForm.id
                    // this.editForm.countyCode = addressForm.countyCode
                    // this.editForm.contactPhone = addressForm.contactPhone
                    // this.editForm.companyId = addressForm.companyId
                    // this.editForm.contactName = addressForm.contactName
                    // this.editForm.isDefault = addressForm.isDefault
                    // this.editForm.detailAddress = addressForm.detailAddress

                }
            },
            del(id) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then((res) => {
                    deleteAddress({id: id}).then(res => {
                        if (res.data.code === '200') {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                            this.getList(this.addressForm.companyId)

                            this.$emit('refreshDataList')
                        }
                    })
                })
            },
            // this.addressForm.companyId
            getList(companyId) {
                this.loading = true
                getCompanyArea({
                    companyId: companyId,
                    pageSize: -1,
                    orderBy: 'is_default',
                    orderByAORC: 'desc'
                }).then((res) => {
                    if (res.data.code === '200') {
                        this.tableData = res.data.result.list
                        console.log(this.tableData)
                    }
                    this.loading = false
                    console.log(res.data)
                })
            },

            getArea1(e) {
                if (e.province !== '' && e.city !== '' && e.district !== '') {
                    this.editForm.countyCode = JSON.stringify(e)
                } else {
                    this.editForm.countyCode = ''
                }
            },
            close(type) {
                if (type === 'edit') {
                    this.editVisible = false
                    return
                }
                this.viewVisible = false
            },
            doSubmit() {
                this.$refs['editForm'].validate((valid) => {
                    if (valid) {
                        if (
                            this.editForm.countyCode !== '' &&
                            typeof this.editForm.countyCode !== 'undefined'
                        ) {
                            console.log(this.editForm.countyCode)
                            this.$set(this.editForm, 'props', 0)
                            editCompanyArea(this.editForm).then((res) => {
                                if (res.data.code === '200') {
                                    this.$message({
                                        message: '编辑成功',
                                        type: 'success'
                                    })
                                    this.editVisible = false
                                    this.$emit('refreshDataList')
                                    this.getList(this.addressForm.companyId)
                                }
                            })
                        }
                    }
                })
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex % 2 === 1) {
                    return 'warning-row'
                } else {
                    return 'success-row'
                }
            }
        }
    }
</script>
<style lang="scss" scoped>
    .title {
        font-size: 16px;
        font-weight: 400;
        color: #333333;
    }

    ::v-deep .el-dialog > .el-dialog__body {
        padding: 15px 20px !important;
        padding-bottom: 15px;
        padding-bottom: 10px !important;
        font-size: 16px !important;
        overflow: auto;
        color: #333333 !important;

        p {
            margin: 0;
        }

        .title {
            display: flex;

            p:first-child {
                flex: 1;
                line-height: 30px;
            }

            .el-button {
                min-width: 110px;
                height: 30px;
                line-height: 30px;
                margin-right: 0;
            }
        }
    }

    .addressDialog ::v-deep .el-dialog__footer {
        margin-top: -29px;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }

    ::v-deep .el-table .warning-row {
        background: #f7f7f7;
    }

    .container2 {
    }

    .container2 :nth-child(2) ::v-deep .el-dialog {
        top: 25%;
    }
</style>
